package com.maweirdos.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.maweirdos.gulimall.common.exception.RRException;
import com.maweirdos.gulimall.member.dao.MemberLevelDao;
import com.maweirdos.gulimall.member.entity.MemberLevelEntity;
import com.maweirdos.gulimall.member.exception.PhoneException;
import com.maweirdos.gulimall.member.exception.UsernameException;
import com.maweirdos.gulimall.member.vo.MemberUserLoginVo;
import com.maweirdos.gulimall.member.vo.MemberUserRegisterVo;
import com.maweirdos.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maweirdos.gulimall.common.utils.PageUtils;
import com.maweirdos.gulimall.common.utils.Query;

import com.maweirdos.gulimall.member.dao.MemberDao;
import com.maweirdos.gulimall.member.entity.MemberEntity;
import com.maweirdos.gulimall.member.service.MemberService;

import javax.annotation.Resource;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Resource
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberUserRegisterVo vo) {
        MemberEntity memberEntity = new MemberEntity();

        //设置默认等级

        MemberLevelEntity levelEntity = memberLevelDao.selectOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));
        memberEntity.setLevelId(levelEntity.getId());

        //设置其它的默认信息
        //检查用户名和手机号是否唯一。感知异常，异常机制
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());

        memberEntity.setNickname(vo.getUserName());
        memberEntity.setUsername(vo.getUserName());
        //密码进行MD5加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setGender(0);
        memberEntity.setCreateTime(new Date());

        //保存数据
        this.baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneException {
        Integer phoneCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));

        if (phoneCount > 0) {
            throw new PhoneException();
        }
    }

    @Override
    public void checkUserNameUnique(String userName) throws UsernameException {
        Integer usernameCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));

        if (usernameCount > 0) {
            throw new UsernameException();
        }
    }

    @Override
    public MemberEntity login(MemberUserLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if (memberEntity != null) {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(password, memberEntity.getPassword());
            if (matches) {
                return memberEntity;
            }
        }else {
            return null;
        }
        return null;
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {

        //登录和注册合并逻辑
        //备注：视频中“微博”社交不需要Access_token也可以获取用户uid，而gitee则需要再发带token请求
        //2.1 查询当前社交用户的社交账号信息(uid,昵称，性别等)
        String url = "https://gitee.com/api/v5/user?access_token=" + socialUser.getAccess_token();
        // 使用HttpClient 发送post请求
        HttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        if(response.getStatusLine().getStatusCode() == 200){
            String json = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(json);
            String uid = jsonObject.get("id").toString();
            //1.判断当前社交用户是否已经登录过系统
            MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_id", uid));
            if(memberEntity !=null){
                //1.用户有注册记录,更新信息
                MemberEntity updateDate = new MemberEntity();
                updateDate.setId(memberEntity.getId());
                updateDate.setAccessToken(socialUser.getAccess_token());
                updateDate.setExpiresIn(Long.parseLong(socialUser.getExpires_in()));
                //...其他的不重要，更不更新无所谓
                this.baseMapper.updateById(updateDate);

                memberEntity.setAccessToken(socialUser.getAccess_token());
                memberEntity.setExpiresIn(Long.parseLong(socialUser.getExpires_in()));
                return memberEntity;
            }else{
                //2.没有查到当前社交用户记录，就需要注册一个
                MemberEntity register = new MemberEntity();
                try{
                    String userName = jsonObject.get("login").toString();
                    String nickName = jsonObject.get("name").toString();
                    if (jsonObject.get("email") != null) {
                        String email = jsonObject.get("email").toString();
                        register.setEmail(email);
                    }
                    String socialId = jsonObject.get("id").toString();
                    //.....等等信息
                    register.setUsername(userName);
                    register.setNickname(nickName);

                    register.setSocialId(socialId);
                }catch (Exception e){
                    /**
                     * 远程查询昵称这些不重要的，即是出现问题也可以忽略
                     */
                }
                register.setAccessToken(socialUser.getAccess_token());
                register.setExpiresIn(Long.parseLong(socialUser.getExpires_in()));
                this.baseMapper.insert(register);
                return register;
            }
        }else {
            throw new RRException(response.getStatusLine().getReasonPhrase(),response.getStatusLine().getStatusCode());
        }
    }

    @Override
    public MemberEntity login(String accessTokenInfo) {
        return null;
    }


}